package org.harsh.transmission.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import org.harsh.transmission.common.*;
import org.harsh.transmission.common.codec.*;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
public class UdpServerChannelInitilizer extends ChannelInitializer<NioDatagramChannel> {

    private InetSocketAddress inetSocketAddress;

    public UdpServerChannelInitilizer(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }

    public UdpServerChannelInitilizer() {
        this.inetSocketAddress = null;
    }

    /**
     * Udp
     * @param channel
     * @throws Exception
     */
    @Override
    protected void initChannel(NioDatagramChannel channel) throws Exception {
        ChannelPipeline p = channel.pipeline();
        p.addLast(GlobalTraffic.getInstance())
                .addLast("channelTraffic", new ChannelTrafficShapingHandler(16384, 16384, 1))
                .addLast(new DatagramPacketCodec(inetSocketAddress))
                .addLast("msgCryptCodec",new PlainCryptMsgPackCodec())
                .addLast("msgPackDecoder",new MsgPackDecoder())
                .addLast("msgPackEncoder",new MsgPackEncoder())
                .addLast("PlainMsgCodec", new PlainMsgCodec())
                .addLast("fileCodec", new FileMsgCodec());
    }
}
